"""
Case Type   : 分区表锁降级
Case Name   : 显示事务truncate分区,通过分区值所在分区删除不提交,其他分区查询的执行成功
Create At   : 2021/11/4
Owner       : opentestcase001
Description :
    1、创建范围分区表,插入数据;
    2、session1中开启事务，通过分区值所在分区删除分区数据，待查询后提交;
    3、session2中同时执行对其他分区的查询计划;
    4、清理环境;
Expect      :
    1、创建范围分区表成功,插入数据成功;
    2、session1中清空分区数据成功,事务提交成功;
    3、session2中同时执行查询成功;
    4、清理环境成功;
History     :
    优化用例,增加等待查询时间,避免sql执行时长不一致执行失败，方便定位问题
"""

import unittest
import os
import time
from testcase.utils.ComThread import ComThread
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.CommonSQL import CommonSQL
from testcase.utils.Logger import Logger


class LockLevel(unittest.TestCase):

    def setUp(self):
        self.log = Logger()
        self.log.info(f"-----{os.path.basename(__file__)} start-----")
        self.constant = Constant()
        self.comsh = CommonSH('PrimaryDbUser')
        self.comSQL = CommonSQL('PrimaryDbUser')
        self.tab_name = 't_locklevel_0121'
        self.i_function_name = 'f_insert_locklevel_0121'

    def test_lock_level(self):
        self.log.info('------创建插入数据函数------')
        func_var = 'pvar'
        func_sql1 = f'''insert into {self.tab_name} values({func_var},1);'''
        insert_func = self.comSQL.create_func(self.i_function_name,
                                              execute_sql=func_sql1,
                                              var=func_var,
                                              start=20000,
                                              end=80000,
                                              step=20000)
        self.log.info(insert_func)
        self.assertTrue(self.i_function_name in insert_func)

        text = '------step1:创建范围分区表,插入数据; expect:成功------'
        create_cmd = f'''drop table if exists {self.tab_name};
            create table {self.tab_name} (id1 int,id2 int) 
            partition by range (id1)
            (partition p00 values less than (20000),
             partition p01 values less than (40000),
             partition p02 values less than (60000));
            select {insert_func}(100);
            select {insert_func}(20100);
            select {insert_func}(40100);'''
        self.log.info(create_cmd)
        create_msg = self.comsh.execut_db_sql(create_cmd)
        self.log.info(create_msg)
        self.assertTrue(self.constant.CREATE_TABLE_SUCCESS in create_msg
                        and create_msg.count(self.i_function_name) == 3,
                        '执行失败:' + text)

        text = '---step2:session1中开启事务,通过分区值删除分区数据,不提交; expect:成功---'
        self.log.info(text)
        update_cmd = f'''start transaction;
            select current_time;
            alter table {self.tab_name} truncate partition for(19999);
            select count(*) from {self.tab_name} partition for(19999);
            select pg_sleep(10);
            select current_time;
            commit;'''
        session_1 = ComThread(self.comsh.execut_db_sql, args=(update_cmd, ''))
        session_1.setDaemon(True)
        session_1.start()
        time.sleep(0.5)

        text = '---step3:session2中执行全表的查询; expect:成功---'
        self.log.info(text)
        select_cmd = f'''select pg_sleep(2);
        select current_time;
        select count(*) from {self.tab_name};
        select current_time;'''
        session_2 = ComThread(self.comsh.execut_db_sql, args=(select_cmd,))
        session_2.setDaemon(True)
        session_2.start()

        self.log.info('------session2执行结果------')
        session_2.join(55)
        session_2_res = session_2.get_result()
        self.log.info(session_2_res)
        self.assertEqual(19, len(session_2_res.splitlines()), "执行失败:" + text)
        self.assertTrue('202' in session_2_res.splitlines()[12],
                        "执行失败:" + text)

        text = '------session1执行结果------'
        self.log.info(text)
        session_1.join(60)
        session_1_res = session_1.get_result()
        self.log.info(session_1_res)
        self.log.info(session_1_res.splitlines())
        self.assertEqual(24, len(session_1_res.splitlines()), "执行失败:" + text)
        self.assertTrue(self.constant.ALTER_TABLE_MSG in session_1_res
                        and self.constant.COMMIT_SUCCESS_MSG in session_1_res,
                        "执行失败:" + text)

    def tearDown(self):
        text = '------step4:清理环境; expect:成功------'
        self.log.info(text)
        drop_cmd = f'''drop table {self.tab_name} cascade;
            drop function {self.i_function_name};'''
        drop_msg = self.comsh.execut_db_sql(drop_cmd)
        self.log.info(drop_msg)
        self.assertTrue(self.constant.DROP_FUNCTION_SUCCESS_MSG in drop_msg
                        and self.constant.DROP_TABLE_SUCCESS in drop_msg,
                        '执行失败' + text)
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
